package com.example.villagedevelop.generator.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.villagedevelop.generator.entity.VideoHouse;
import com.example.villagedevelop.generator.mapper.VideoHouseMapper;
import com.example.villagedevelop.generator.service.VideoHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/videoHouse")
public class VideoHouseController {

    @Autowired
    VideoHouseService videoHouseService;
    @Autowired
    VideoHouseMapper mapper;

    //根据id将视频的url存入数据库并存储到服务器
    @PostMapping("/saveVideo")
    public String upload(int id, MultipartFile video){
        if (video.getSize()>0){//判断文件是否为空
            String path = "D:/picture/video";

            //获取上传的文件名
            String name = video.getOriginalFilename();
            File file = new File(path,name);

            String suffixName = name.substring(name.lastIndexOf("."));
            List<String> extList = Arrays.asList(".mp4", ".avi", ".gif");
            if (!extList.contains(suffixName)) {
                return "视频格式非法";
            }

            try {
                video.transferTo(file);//将video保存进file文件
                VideoHouse videoHouse = new VideoHouse();
                String name_random = String.valueOf(System.currentTimeMillis());
                name_random += (int)((Math.random() * 9 + 1)* 10000);
                videoHouse.setVideoFile("http://zbnczy.com/video/"+name_random+suffixName);
                videoHouse.setHId(id);
                videoHouseService.save(videoHouse);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "ok!";
    }

    //查询视频，视频转换成url格式
    @GetMapping("/getVideo")
    public String getVideo(int id){
        VideoHouse videoHouse = videoHouseService.getById(id);
        return videoHouse.getVideoFile();
    }

    //删除视频
    @GetMapping("/delete")
    public void delete(@RequestParam("video") String video){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("video_file",video);
        mapper.delete(wrapper);
    }



}
